const RxFileWrite = require('rxfile-write')
const upd = require('./upd')
const fs = require('fs')

const pathResolve = require('path').join
const RootPath = pathResolve(__dirname, '/data/auth.txt')

function main() {
  return new Promise((resolve, reject) => {
    RxFileWrite.read(RootPath).then(data => {
      if (!data) getUpd().then(resolve).catch(reject)

      const obj = JSON.parse(data)

      const device = obj.device || {}
      const deviceid = device.deviceid
      if (deviceid) {
        const dateNow = Math.floor(Date.now() / 1000)
        const date = obj.date
        const valid = obj.valid
        if (dateNow >= (date + valid + 1)) {
          getUpd().then(resolve).catch(reject)
        } else {
          resolve()
        }
      } else {
        getUpd().then(resolve).catch(reject)
      }

    }).catch(() => getUpd().then(resolve).catch(reject))
  })
}

function getUpd() {
  return upd()
}

function clearFile() {
  fs.unlinkSync(RootPath)
}

module.exports = { main, clearFile }